<template>
  <a-card :body-style="{padding: '24px 32px'}" :bordered="false">
    <!-- <a-page-header title="返回" @back="() => $router.go(-1)" /> -->
    <a-form-model
      :model="info"
      ref="ruleForm"
      :rules="rules"
      @submit.native.prevent
    >
      <a-form-model-item
        label="管理员账号"
        :labelCol="labelCol"
        :wrapperCol="wrapperCol"
        prop="account">
        <a-input size="large" v-model="info.account" />
      </a-form-model-item>
      <!-- <a-form-model-item
        label="角色"
        :labelCol="labelCol"
        :wrapperCol="wrapperCol"
        prop="roleId">
        <a-select size="large" v-model="info.roleId">
          <a-select-option value="">
            请选择
          </a-select-option>
          <a-select-option :value="item.id" v-for="item in roleList" :key="item.id">
            {{ item.roleName }}
          </a-select-option>
        </a-select>
      </a-form-model-item> -->
      <a-form-model-item
        label="姓名"
        :labelCol="labelCol"
        :wrapperCol="wrapperCol"
        prop="realName">
        <a-input size="large" v-model="info.realName" />
      </a-form-model-item>
      <a-form-model-item
        label="密码"
        :labelCol="labelCol"
        :wrapperCol="wrapperCol"
        prop="password"
        :required="id ? false : true">
        <a-input size="large" v-model="info.password" type="password" />
      </a-form-model-item>
      <a-form-model-item
        label="确认密码"
        :labelCol="labelCol"
        :wrapperCol="wrapperCol"
        prop="confirmpassword"
        :required="id ? false : true">
        <a-input size="large" v-model="info.confirmpassword" type="password" />
      </a-form-model-item>
      <!-- <a-form-model-item
        label="手机号码"
        :labelCol="labelCol"
        :wrapperCol="wrapperCol"
        prop="telphone">
        <a-input size="large" v-model="info.telphone" />
      </a-form-model-item>
      <a-form-model-item
        label="性别"
        :labelCol="labelCol"
        :wrapperCol="wrapperCol"
        prop="gender">
        <a-radio-group v-model="info.gender">
          <a-radio :value="0">未知</a-radio>
          <a-radio :value="1">男</a-radio>
          <a-radio :value="2">女</a-radio>
        </a-radio-group>
      </a-form-model-item> -->
      <a-form-model-item
        label="状态"
        :labelCol="labelCol"
        :wrapperCol="wrapperCol"
        prop="status">
        <a-radio-group v-model="info.status">
          <a-radio value="1">开启</a-radio>
          <a-radio value="0">关闭</a-radio>
        </a-radio-group>
      </a-form-model-item>
      <a-form-model-item
        :wrapperCol="{ span: 24 }"
        style="text-align: center"
      >
        <a-button
          htmlType="submit"
          type="primary"
          :loading="state.submitBtn"
          :disabled="state.submitBtn"
          @click="onSubmit">保存</a-button>
        <a-button style="margin-left: 8px" @click="() => $router.go(-1)">取消</a-button>
      </a-form-model-item>
    </a-form-model>
  </a-card>
</template>

<script>
import pick from 'lodash.pick'

export default {
  name: 'AdminEdit',
  data () {
    const validatePass = (rule, value, callback) => {
      if (this.id) { // 修改时如果输入确认密码，则密码必填
        if (value === '') {
          if (this.info.confirmpassword !== '') {
            callback(new Error('密码必填'))
          }
          callback()
        } else {
          if (this.info.confirmpassword !== '') {
            this.$refs.ruleForm.validateField('confirmpassword')
          }
          callback()
        }
      } else {
        if (value === '') {
          callback(new Error('密码必填'))
        } else {
          if (this.info.confirmpassword !== '') {
            this.$refs.ruleForm.validateField('confirmpassword')
          }
          callback()
        }
      }
    }
    const validatePass2 = (rule, value, callback) => {
      if (this.id) { // 修改时如果输入密码，则确认密码必填
        if (value === '') {
          if (this.info.password !== '') {
            callback(new Error('请再次输入密码'))
          }
          callback()
        } else if (value !== this.info.password) {
          callback(new Error('两次密码不一致'))
        } else {
          callback()
        }
      } else {
        if (value === '') {
          callback(new Error('请再次输入密码'))
        } else if (value !== this.info.password) {
          callback(new Error('两次密码不一致'))
        } else {
          callback()
        }
      }
    }
    return {
      id: this.$route.params.id ? parseInt(this.$route.params.id) : '',
      info: {},
      rules: {
        account: [
        { required: true, message: '请输入账号', trigger: ['blur', 'change'] }],
        status: [{ required: true, message: '状态必选', trigger: ['blur', 'change'] }],
        password: [{ validator: validatePass, message: '请输入密码', trigger: ['blur', 'change'] }, { min: 6, max: 18, message: '密码6-18个字符', trigger: ['blur'] }],
        confirmpassword: [{ validator: validatePass2, trigger: ['blur', 'change'] }],
        realName: [{ required: true, message: '姓名必填', trigger: ['blur', 'change'] }, { min: 2, message: '姓名大于2个字符', trigger: ['blur'] }]
        // roleId: [{ required: true, message: '角色必选', trigger: ['blur', 'change'] }]
      },
      state: {
        submitBtn: false
      },
      labelCol: { lg: { span: 7 }, sm: { span: 7 } },
      wrapperCol: { lg: { span: 10 }, sm: { span: 17 } },
      roleList: [],
      loading: false
    }
  },
  mounted () {
    // 获取信息
    this.formInit()
    // 获取角色列表
    // this.getRoleList()
  },
  methods: {
    formInit () {
      // 获取信息
      if (this.id) {
        this.getInfo()
      } else {
        this.info = {
          account: '',
          password: '',
          confirmpassword: '',
          realName: '',
          status: '1'
        }
      }
    },
    // 获取角色列表
    getRoleList () {
      const params = {
        pageNo: 1,
        pageSize: 100
      }
      this.$common.handlePost('/jdsysAdminBody/selectPageList', Object.assign({}, params)).then(data => {
        if (data.code === 200) {
          const result = data.result
          this.roleList = result.records
        }
      }).catch(() => {
        this.$notification.error({
          message: '错误',
          description: '请求信息失败，请重试'
        })
      })
    },
    // 编辑信息
    getInfo () {
      this.$common.handleGet('/admin/' + this.id).then(data => {
        if (data.code === 200) {
          const result = data.data
          const formData = pick(result, ['adminId', 'account', 'realName', 'status'])
          this.info = formData
        } else {
          this.$message.error(data.message)
          // 跳转到目的路由
          this.$router.push({ name: 'AdminList' })
        }
      })
    },
    // 提交
    onSubmit () {
      const {
        state,
        handleFormData
      } = this
      state.submitBtn = true
      // 验证表单
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          this.id ? handleFormData('/admin/' + this.id) : handleFormData('/admin/add')
        } else {
          setTimeout(() => {
            state.submitBtn = false
          }, 600)
        }
      })
    },
    // 表单数据处理
    handleFormData (url) {
      const info = { ...this.info }
      delete info.confirmpassword
      this.$common.handlePost(url, info)
        .then(res => {
          if (res.code === 200) {
            this.$message.success(res.message, 1, () => {
              // 跳转到目的路由
              this.$router.push({ name: 'AdminList' })
            })
          } else {
            this.$message.error(res.message)
          }
        })
        .catch(() => {
          this.$notification.error({
            message: '错误',
            description: '请求信息失败，请重试'
          })
        })
        .finally(() => {
          this.state.submitBtn = false
        })
    }
  }
}
</script>
